﻿using System;
using System.Linq;
using System.Windows.Input;
using Avivo.Tools.Sprite.Models;

namespace Avivo.Tools.Sprite
{
	public class AddSpriteCommand : ICommand
	{
		#region Private members
		private SpriteModel model;
		private SpriteViewModel parent;
		#endregion

		#region Constructor
		public AddSpriteCommand(SpriteModel model, SpriteViewModel parent)
		{
			this.model = model;
			this.parent = parent;
		}
		#endregion

		#region ICommand Members
		public bool CanExecute(object parameter)
		{
			return true;
		}

		public event EventHandler CanExecuteChanged;

		public void Execute(object parameter)
		{
			//Create a new item
			var model = new SpriteModel(this.parent);
			string template = this.model.Template ?? this.parent.TemplateList.FirstOrDefault();
			model.Name = template;
			model.Template = template;

			//Ensure that new item has unique name
			int counter = 1;
			while (this.parent.Sprites.Count(x => x.Name == model.Name) > 0)
			{
				model.Name = string.Format("{0}-{1}", template, counter++);
			}

			//Add to the list
			int index = this.parent.Sprites.IndexOf(this.model);
			if (index >= 0)
			{
				this.parent.Sprites.Insert(index + 1, model);
			}
			else
			{
				this.parent.Sprites.Add(model);
			}
		}
		#endregion
	}
}
